package com.priox.sigar.util;

import com.priox.sigar.domain.model.constantes.PathConstant;
import com.priox.sigar.server.infrastructure.persistence.exception.ApplicationException;

import java.io.*;

public class FileUtil {

    public static String getFileName(String fileFullName) throws Exception {
        int indexStart1 = fileFullName.lastIndexOf("/");
        int indexStart2 = fileFullName.lastIndexOf("\\");

        int indexStart = Math.max(indexStart1, indexStart2);
        String fileName = fileFullName.substring(indexStart + 1);
        indexStart = fileName.lastIndexOf(".");
        fileName = fileName.substring(0, indexStart);
        return fileName;
    }

    public static byte[] toByte(File file) throws IOException {
        FileInputStream fis = new FileInputStream(file);
        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        try {
            int c = 0;
            while ((c = fis.read()) != -1) {
                baos.write(c);
            }
            byte[] byteReturn = baos.toByteArray();
            return byteReturn;
        } finally {
            fis.close();
            baos.close();
        }
    }

    public static void copyFile(String fileName,InputStream in, String newFileName) {
        try {

            OutputStream out = new FileOutputStream(new File(PathConstant.DIR_TMP + File.separator + newFileName));
            int read = 0;
            byte[] bytes = new byte[1024];
            while ((read = in.read(bytes)) != -1) {
                out.write(bytes, 0, read);
            }
            in.close();
            out.flush();
            out.close();
        } catch (IOException e) {
            throw new ApplicationException("Problemas al copiar el archivo:" + fileName + " a la ruta:" + PathConstant.DIR_TMP, e);
        }
    }
}
